﻿
@{
    ViewBag.Title = "Manage Users";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@if (User != null && DoeLibsMVC.Security.SecurityHelper.currentUserIsInStaffGroup())
{
    <div id="PresentationBox">
        <h2 class="centeredHeaderText" id="deleteHeaderText"></h2>

		<div class="generalTextDiv" style="text-align: left">
			<span style="margin-right: 20px">Transfer loanables to: </span>
			<select id="newUser" class="generalSelectElement"></select>
			<input id="transferAndDeleteBtn" type="button" class="generalBtn" value="transfer and delete" />
		</div>

		<table class="DataPresentationtable" id="resultTable">
            <tr>
                <td><center><img src="/Content/images/loading.gif" />loading data...</center></td>
            </tr>
		</table>
    </div>

	<script type="text/javascript">

		var tabletest = [];
		var checkBoxTest = [];

		$(document).ready(function () {

			var currentModel = [];
			var submitButton = [];
			var table = [];
			var header = [];
			var selector = [];

			function handleGetData(model) {

				currentModel = model;
				header.innerHTML = 'Delete ' + model.FromUser.FirstName + ' ' + model.FromUser.LastName;

				var selectorBody = "";
				for (var i = 0; i < model.StaffMembers.length; i++) {
					selectorBody += '<option value="' + model.StaffMembers[i].Value + '">' + model.StaffMembers[i].Text + '</option>';
				}
				selector.innerHTML = selectorBody;

				dataSet = [];

				if (model.UserLoanables.Count == 0)
				{
					var table = document.getElementById('resultTable');
					table.innerHTML = "<tbody><tr><td>No loanables found for the user ...</td></tr></tbody>";
					return;
				}

				$.each(model.UserLoanables, function (key, val) {

					var object = [];
					object.Transfer = '<input type="checkbox" checked="true" value="' + val.LoanableId + '" class="deleteCheckBox" />';
					object.Title = val.Title.BookTitle;
					object.DoeLibsId = val.Barcode;
					object.Location = val.Location + ' (' + val.Category.Name + ')';
					dataSet.push(object);
				});

				columns = [
					{ "data": "Transfer", "title": "Transfer", "sWidth": "10%" },
					{ "data": "Title", "title": "Title", "sWidth": "45%" },
					{ "data": "DoeLibsId", "title": "DoeLibs identifier", "sWidth": "20%" },
					{ "data": "Location", "title": "Location", "sWidth": "25%" },
				];
				$('#resultTable').DataTable({
					"bFilter": false,
					"bPaginate": false,
					"data": dataSet,
					"retrieve": true,
					"fnDrawCallback": function () {
						if (Math.ceil((this.fnSettings().fnRecordsDisplay()) / this.fnSettings()._iDisplayLength) > 1) {
							$('#searchTable_paginate').css("display", "block");
						} else {
							$('#searchTable_paginate').css("display", "none");
						}
					},
					"columns": columns
				});
			}

			function onTransferAndDeleteClick()
			{
				//table = $('#resultTable').dataTable();
				console.log(currentModel);
				var model = getPostData();
				console.log(model);

				$.ajax({
					url: "/api/userdelete/" + '@ViewBag.DeleteUserId',
					type: "DELETE",
					contentType: 'application/json; charset=utf-8',
					data: JSON.stringify(model),
					beforeSend: function (xhr) {
						xhr.setRequestHeader("Authorization", getAuthorizationHeader('@User.UserId', ''));
				}
				}).done(function (data) {
					setHttpMessage("User successfully deleted and loanables transfered", true);
					document.location.href = '/User/ManageUsers';
				}).fail(function (data) {
					setHttpMessage("Technical issues please try again", false);
					location.reload();
				});
			}

			function getPostData()
			{
				currentModel.ToUserId = selector.value;
				currentModel.TransferLoanablesIds = [];
				/*for (var i = 0; i < table.fnSettings().fnRecordsTotal() ; i++)
				{
					var checkBox = table.fnGetData(i, 0);

					checkBoxTest = checkBox;
					tabletest = table;

					if ($(checkBox).attr('value') == '1')
						currentModel.TransferLoanablesIds[i] = $(checkBox).attr('id');
				}*/
				var counter = 0;
				$('.deleteCheckBox').each(function (index, element) {
					if (element.checked == true)
					{
						currentModel.TransferLoanablesIds[counter] = element.value;
						counter++;
					}
				});

				return currentModel;
			}

			header = document.getElementById('deleteHeaderText');
			selector = document.getElementById('newUser');
			submitButton = document.getElementById('transferAndDeleteBtn');
			table = [];

			$.ajax({
				url: "/api/userdelete/" + '@ViewBag.DeleteUserId',
				type: "GET",
				beforeSend: function (xhr) {
					xhr.setRequestHeader("Authorization", getAuthorizationHeader('@User.UserId', ''));
				}
			}).done(function (data) {
				handleGetData(data);
			}).fail(function () {
				document.getElementById('deleteHeaderText').innerHTML = 'User could not be found.';
			});

			$('#transferAndDeleteBtn').click(onTransferAndDeleteClick);
		});

	</script>
}